package com.lagou.edu.service.impl;

import com.lagou.edu.dao.TokenDao;
import com.lagou.edu.dao.UserDao;
import com.lagou.edu.pojo.Token;
import com.lagou.edu.pojo.User;
import com.lagou.edu.service.*;
import com.lagou.edu.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private TokenDao tokenDao;
    @Lazy
    @Autowired
    private CodeServiceFeign codeService;

    @Override
    public String register(String email, String password, String code) {
        // 调用 code 服务校验验证码
        int checkResult = codeService.validate(email, code);
        if (checkResult > 0) {
            return "" + checkResult;
        }
        if(isRegistered(email)) {
            return "4";
        }
        User user = new User();
        user.setCreatetime(new Date());
        user.setEmail(email);
        user.setPassword(MD5.MD5Encode(password));
        userDao.save(user);
        return "success";

    }

    @Override
    public boolean isRegistered(String email) {
        return userDao.findByEmail(email) != null;
    }

    @Override
    @Transactional
    public String login(String email, String password) {
        String encryptedPassword = MD5.MD5Encode(password);
        User user = userDao.findByEmailAndPassword(email, encryptedPassword);
        if(user == null) {
            return "false";
        }
        Token token = tokenDao.findByEmail(email);
        if(token == null) {
            token = new Token();
            token.setEmail(email);
            token.setToken(UUID.randomUUID().toString());
            tokenDao.save(token);
        } else {
            /** 更新 token  */
            token.setToken(UUID.randomUUID().toString());
        }
        return email;
    }

    @Override
    public String info(String token) {
        Token userToken = tokenDao.findByToken(token);
        if(userToken == null) {
            return "";
        }
        return userToken.getEmail();
    }

    @Override
    public String loadToken(String email) {
        Token userToken = tokenDao.findByEmail(email);
        if(userToken == null) {
            return "";
        }
        return userToken.getToken();
    }
}
